﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using entity = AgileDashboard.Entities;
using AgileDashboard.Data.Converters;

namespace AgileDashboard.Data
{
    public class WorkItemDataSource
    {

        public List<WorkItem> GetWorkItemsfromQuery(string queryText, Project project)
        {

            queryText = queryText.Replace("@project", String.Format("'{0}'", project.Name));


            List<WorkItem> workItems = new List<WorkItem>();


            Query query = new Query(project.Store, queryText);
            WorkItemCollection wc = query.RunQuery();

            foreach (WorkItem wi in wc)
            {
                workItems.Add(wi);



            }

            return workItems;
        }



        public WorkItem GetWorkItem(int id, Project proj)
        {
            string query = string.Format("Select ID from WorkItems where [ID] = {0}", id);
            WorkItemCollection workItems = proj.Store.Query(query);
            if (workItems != null)
                if (workItems.Count > 0)
                    return workItems[0];
            return null;
        }



        /// <summary>
        /// Get a set of WorkItems matching a set of IDs
        /// </summary>
        /// <param name="TeamProjectCollection">The team project collection.</param>
        /// <param name="batchReadParams">A collection of the IDs whose workitems to get.</param>
        /// <returns>A dictionary of ID/WorkItem pairs.</returns>
        public WorkItemCollection GetWorkItems(Project proj, BatchReadParameterCollection batchReadParams)
        {
            WorkItemStore wiStore = proj.Store;
            Query query = new Query(wiStore, "SELECT * FROM WorkItems", batchReadParams);
            return query.RunQuery();
        }




        public List<entity.WorkItem> GetWorkItemsfromQuery(string queryText, Project proj, bool recursive)
        {


            List<WorkItem> workItems = GetWorkItemsfromQuery(queryText, proj);


            List<entity.WorkItem> myWorkItems = new List<entity.WorkItem>();
            foreach (WorkItem workItem in workItems)
            {


                entity.WorkItem item = WorkItemFactory.CreateWorkItem(workItem, 0);

                myWorkItems.Add(item);
                if (recursive)
                {
                    GetChildWorkItems(proj, workItem.Id, item, 1);
                }
            }
            return myWorkItems;

        }



        /// <summary>
        /// Get the child WorkItems of a given workitem ID. 
        /// </summary>
        /// <param name="orderBy">The Order By clause. Don't include "ORDER BY".</param>
        /// <param name="parentId">The ID of the parent whose child items to get.</param>
        /// <param name="projectName">The name of the project.</param>
        /// <param name="whereClause">The Where clause. Don't include the "WHERE" or the "AND".</param>
        /// <param name="workItemType">The type of WorkItem to retrieve.</param>
        /// <returns>A WorkItemCollection of the child WorkItems of the parent ID.</returns>
        public void GetChildWorkItems(Project proj, int parentId, entity.WorkItem workItem, int level)
        {
            WorkItemStore wiStore = proj.Store;
            string workItemType = "User Story";

            string wiql = string.Format("SELECT [System.Id], [System.Links.LinkType], [System.Title] FROM WorkItemLinks WHERE ([Source].[System.Id] = {2}) And ([System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward') And ([Target].[System.TeamProject] = '{0}'  AND  ([Target].[System.WorkItemType] = '{1}' Or [Target].[System.WorkItemType] = '{3}') )  mode(MustContain)",
                proj.Name, workItemType, parentId, "Task");

            // Query to get results as list of WorkItem links.
            Query query = new Query(wiStore, wiql);
            WorkItemLinkInfo[] workItemLinkInfoArray = query.RunLinkQuery();

            // Create a list of the IDs to retrieve.
            BatchReadParameterCollection batchReadParams = new BatchReadParameterCollection();
            foreach (WorkItemLinkInfo info in workItemLinkInfoArray)
                batchReadParams.Add(new BatchReadParameter(info.TargetId));

            if (batchReadParams.Count > 0)
                // Remove the first one. That's the parent.
                batchReadParams.RemoveAt(0);

            // Get the WorkItems from the IDs.
            WorkItemCollection workItemCollection = GetWorkItems(proj, batchReadParams);
            workItem.LinkedWorkedItems = new List<Entities.WorkItem>();

            int recursionLevel = level;

            foreach (WorkItem wi in workItemCollection)
            {
                entity.WorkItem myWorkItem = WorkItemFactory.CreateWorkItem(wi, level);
                workItem.LinkedWorkedItems.Add(myWorkItem);
                GetChildWorkItems(proj, wi.Id, myWorkItem, recursionLevel + 1);

            }

        }





    }
}
